import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
    userRoles: []
  }),
  getters: {
    isAuthenticated: (state) => !!state.token,
    isAdmin: (state) => state.userRoles.includes('admin')
  },
  actions: {
    // 初始化 - 从本地存储加载用户信息
    init() {
      const savedUser = localStorage.getItem('user')
      const savedRoles = localStorage.getItem('roles')
      
      if (savedUser) {
        this.user = JSON.parse(savedUser)
      }
      
      if (savedRoles) {
        this.userRoles = JSON.parse(savedRoles)
      }
    },
    
    // 登录
    async login(email, password) {
      try {
        // 模拟API请求
        const response = await new Promise((resolve) => {
          setTimeout(() => {
            // 模拟不同角色的用户
            let user, roles
            if (email === 'admin@example.com') {
              user = { id: 1, name: '管理员', email }
              roles = ['admin']
            } else {
              user = { id: 2, name: '普通用户', email }
              roles = ['user']
            }
            
            resolve({
              success: true,
              data: {
                token: 'mock-jwt-token-' + Date.now(),
                user,
                roles
              }
            })
          }, 500)
        })
        
        if (response.success) {
          this.token = response.data.token
          this.user = response.data.user
          this.userRoles = response.data.roles
          
          // 保存到本地存储
          localStorage.setItem('token', this.token)
          localStorage.setItem('user', JSON.stringify(this.user))
          localStorage.setItem('roles', JSON.stringify(this.userRoles))
          
          return true
        }
        return false
      } catch (error) {
        console.error('登录失败:', error)
        return false
      }
    },
    
    // 注册
    async register(userData) {
      try {
        // 模拟API请求
        const response = await new Promise((resolve) => {
          setTimeout(() => {
            resolve({
              success: true,
              message: '注册成功'
            })
          }, 500)
        })
        
        return response.success
      } catch (error) {
        console.error('注册失败:', error)
        return false
      }
    },
    
    // 退出登录
    logout() {
      this.user = null
      this.token = null
      this.userRoles = []
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('roles')
    }
  }
})
